<template>
  <!--这些东西都是示例，可以直接删除-->
  <div>
    <h1>主页</h1>
    <button @click="goToAnotherPage('/login')">跳转到登录页</button>
    <button @click="goToAnotherPage('/register')">跳转到注册页</button>
    <button @click="goToAnotherPage('/index')">跳转到主页</button>
    <button @click="goToAnotherPage('/change_password')">跳转到修改密码页</button>
    <button @click="goToAnotherPage('/forgot_password')">跳转到忘记密码页</button>
    
    <div class="api-test-section">
      <button @click="testapi">点击测试API</button>
      <div class="result">{{ apiResult }}</div>
      <div v-if="loading" class="loading">加载中...</div>
      <div v-if="error" class="error-message">{{ error }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

// 路由实例
const router = useRouter();

// 响应式状态
const apiResult = ref('');
const loading = ref(false);
const error = ref(null);

// 页面跳转方法
const goToAnotherPage = (path) => {
  router.push(path);
};

// API 测试方法
const testapi = async () => {
  try {
    loading.value = true;
    error.value = null;
    const params = new URLSearchParams();
    params.append('value', 'vue');

    const response = await axios({
      url: 'http://localhost:5432/namecard/search/some/',
      method: 'post',
      data: {
        value: 'vue' ,
        id:'6',
        password:'123456',
        oldholdername: '测试名片夹4',
        newholdername: '测试名片夹5',
        holdername:'测试名片夹',
        name:'李四',
        phone:'12345678901',
      }, // 使用JSON格式
      headers: { 
        'Content-Type': 'application/json' 
      }
    });//该语句用于访问api，后端的ip请参见后端项目
    apiResult.value = response.data;//该语句用于将请求结果赋值给变量
  } catch (err) {//只要http状态码不是2开头就会抛出错误
    error.value = `请求失败: ${err.message}`;
    apiResult.value = '';
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.api-test-section {
  margin-top: 2rem;
  padding: 1rem;
  border: 1px solid #eee;
  border-radius: 4px;
}

button {
  margin: 0.5rem;
  padding: 0.5rem 1rem;
  cursor: pointer;
}

.loading {
  color: #666;
  margin-top: 0.5rem;
}

.error-message {
  color: #ff4444;
  margin-top: 0.5rem;
}

.result {
  margin-top: 1rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border-radius: 4px;
}
</style>